<?php

namespace app\admin\model\scanwork;

use think\Model;

/**
 * 供应商应付账款模型
 */
class SupplierPayable extends Model
{
    // 表名
    protected $name = 'scanwork_supplier_payable';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'status_text',
        'overdue_status'
    ];
    
    /**
     * 状态列表
     */
    public function getStatusList()
    {
        return [
            'pending' => '待付款',
            'partial' => '部分付款',
            'paid' => '已付清',
            'overdue' => '逾期'
        ];
    }

    /**
     * 状态文本
     */
    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    /**
     * 逾期状态
     */
    public function getOverdueStatusAttr($value, $data)
    {
        if (isset($data['due_date']) && $data['due_date']) {
            $dueDate = strtotime($data['due_date']);
            $today = strtotime(date('Y-m-d'));
            
            if ($dueDate < $today && $data['status'] != 'paid') {
                return 'overdue';
            } elseif ($dueDate == $today) {
                return 'due_today';
            } elseif ($dueDate < strtotime('+7 days') && $dueDate > $today) {
                return 'due_soon';
            }
        }
        return 'normal';
    }

    /**
     * 关联供应商
     */
    public function supplier()
    {
        return $this->belongsTo('Supplier', 'supplier_id', 'id');
    }

    /**
     * 关联采购入库单
     */
    public function purchaseInbound()
    {
        return $this->belongsTo('PurchaseInbound', 'purchase_inbound_id', 'id');
    }

    /**
     * 关联采购记录
     */
    public function purchaseRecord()
    {
        return $this->belongsTo('PurchaseRecord', 'purchase_record_id', 'id');
    }

    /**
     * 关联付款记录
     */
    public function payments()
    {
        return $this->hasMany('SupplierPayment', 'payable_id', 'id');
    }
}
